﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Jackie.Silverliight.SetpBySetp.LiveSearchWebService;

namespace Jackie.Silverliight.SetpBySetp.Html
{
    public partial class LiveSearch : Page
    {
        public LiveSearch()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            LiveSearchWebServiceClient client = new LiveSearchWebServiceClient();
            client.DoSearchCompleted += new EventHandler<DoSearchCompletedEventArgs>(client_DoSearchCompleted);
            client.DoSearchAsync(this.txtQuery.Text);
        }

        void client_DoSearchCompleted(object sender, DoSearchCompletedEventArgs e)
        {
            if(e.Error==null)
            {
                SearchResultItem[] resultItems = e.Result.ToArray();

                HtmlElement result = HtmlPage.Document.GetElementById("result");

                foreach(SearchResultItem item in resultItems)
                {
                    HtmlElement itemElement = HtmlPage.Document.CreateElement("div");
                    itemElement.CssClass = "itemstyle";

                    HtmlElement titleElement = HtmlPage.Document.CreateElement("a");
                    titleElement.SetAttribute("href", item.Url);
                    titleElement.SetAttribute("innerText", item.Title);

                    HtmlElement descriptElement = HtmlPage.Document.CreateElement("div");
                    descriptElement.SetAttribute("innerText", item.Description);

                    HtmlElement urlElement = HtmlPage.Document.CreateElement("span");
                    urlElement.SetAttribute("innerText", item.Url);
                    urlElement.CssClass = "urlstyle";

                    itemElement.AppendChild(titleElement);
                    itemElement.AppendChild(descriptElement);
                    itemElement.AppendChild(urlElement);

                    result.AppendChild(itemElement);
                }
            }
        }

    }
}
